package com.uchedao.seller.ui.user.login;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.uchedao.seller.R;
import com.uchedao.seller.http.Api;
import com.uchedao.seller.http.HttpRequest;
import com.uchedao.seller.manager.UserInfoManager;
import com.uchedao.seller.ui.baidu.BaseFragForBaidu;
import com.uchedao.seller.util.ViewUtil;
import com.uchedao.seller.widget.MyEditView;
import com.uchedao.seller.widget.TitleLayoutView;
import com.uchedao.ulibrary.fragment.FragmentMrg;

import java.util.HashMap;
import java.util.Map;

/**
 * 修改密码
 * Created by zhengxizhen on 15/10/26.
 */
public class ChangePassWordFragment extends BaseFragForBaidu implements View.OnClickListener {

    private static BaseFragForBaidu mInstance = null;

    /**
     * 获取单例
     */
    public static synchronized BaseFragForBaidu getInstance() {
        if (mInstance == null) {
            mInstance = new ChangePassWordFragment();
        }
        return mInstance;
    }

    private String mPhone;

    private TimeCount timeCount;
    private int mStatus = 1;//当前标签
    private final int PHONE = 1;//1 手机号
    private final int VALID_CODE = 2;//2验证码－登录
    private String valid_code;
    private String password;

    private TitleLayoutView ll_title;
    private MyEditView mev_user_phone, mev_valid_code, mev_pwd, mev_valid_phone;
    private View rl_valid_code, rl_valid_phone;
    private Button btn_request_sms;

    @Override
    protected String getActivityTag() {
        return "ChangePassWordFragment";
    }

    @Override
    public int getViewLayoutId() {
        return R.layout.fragment_change_password;
    }

    @Override
    public void initListener() {
        btn_request_sms.setOnClickListener(this);
        mev_user_phone.setButton(this);
        findViewById(R.id.btn_change_password_login).setOnClickListener(this);
        mev_valid_phone.getEt_content().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //修改手机号码，停止之前的倒计时任务，允许请求新的手机验证码
                cancelTimeCount();
            }
        });
    }

    @Override
    public void initData() {
        ll_title.setData(getString(R.string.change_password), this);
        setViewStatus(PHONE);
    }

    @Override
    public void initView() {
        ll_title = (TitleLayoutView) findViewById(R.id.ll_title);
        rl_valid_phone = findViewById(R.id.rl_valid_phone);
        rl_valid_code = findViewById(R.id.rl_valid_code);
        mev_user_phone = (MyEditView) findViewById(R.id.mev_user_phone);
        mev_pwd = (MyEditView) findViewById(R.id.mev_pwd);
        mev_valid_code = (MyEditView) findViewById(R.id.mev_valid_code);
        mev_valid_phone = (MyEditView) findViewById(R.id.mev_valid_phone);
        btn_request_sms = (Button) findViewById(R.id.btn_request_sms);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back:
                FragmentMrg.toBack(mInstance);
                break;
            case R.id.tv_sms:
                if (confirmPhone()) {
                    requestSMS();
                }
                break;
            case R.id.btn_change_password_login:
                if (confirmInfo()) {
                    requestChangePassWord();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 请求修改密码
     */
    private void requestChangePassWord() {
        // 获取验证码，并进入下一个页面
        Map<String, String> map = new HashMap<String, String>();
        map.put("app_name", "buy");
        map.put("mobile", mPhone);
        map.put("password", password);
        map.put("valid_code", valid_code);
        Request request = HttpRequest.getRequest(HttpRequest.POST, Api.Action.USER_PASSWORD, map
                , new Response.Listener<JsonObject>() {
            @Override
            public void onResponse(JsonObject response) {
                UserInfoManager.saveSTATE(false);
                showToast("成功修改密码！");
                toBack(mInstance);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.getMessage() + "", Toast.LENGTH_SHORT).show();
            }
        });
        addQueue(request);
    }

    /**
     * 验证数据是否为空
     */
    private boolean confirmInfo() {
        valid_code = mev_valid_code.getString();
        mPhone = mev_valid_phone.getString();
        password = mev_pwd.getString();
        if (TextUtils.isEmpty(valid_code)
                || TextUtils.isEmpty(mPhone)
                || TextUtils.isEmpty(password)) {
            return false;
        }
        if (mPhone.length() < 11) {
            ViewUtil.showEditError(mev_valid_phone.getEt_content(), getString(R.string.phone_is_error));
            return false;
        }
        return true;
    }

    @Override
    public void onPause() {
        cancelTimeCount();
        super.onPause();
    }

    private void setViewStatus(int tag) {
        mStatus = tag;
        if (mStatus == PHONE) {
            cancelTimeCount();
            ll_title.setTitle(getString(R.string.change_password));
            mev_user_phone.setVisibility(View.VISIBLE);
            rl_valid_code.setVisibility(View.GONE);
            rl_valid_phone.setVisibility(View.GONE);
        } else if (mStatus == VALID_CODE) {
            ll_title.setTitle(getString(R.string.valid_code_title));
            mev_user_phone.setVisibility(View.GONE);
            rl_valid_code.setVisibility(View.VISIBLE);
            rl_valid_phone.setVisibility(View.VISIBLE);
        }
        closeInputMethodManager();
    }

    private boolean confirmPhone() {
        mPhone = mev_user_phone.getString();
        if (TextUtils.isEmpty(mPhone)) {
            return false;
        }
        return true;
    }

    private void requestSMS() {
        // 获取验证码，并进入下一个页面
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", mPhone);
        Request request = HttpRequest.getRequest(HttpRequest.POST, Api.Action.VALID_CODE, map
                , new Response.Listener<JsonObject>() {
            @Override
            public void onResponse(JsonObject response) {
                mev_valid_phone.setETContent(mPhone);
                mev_valid_phone.getEt_content().setTextColor(getResources().getColor(R.color.deep_red));
                //获取下发短信接口请求成功
                setViewStatus(VALID_CODE);
                startThread();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.getMessage() + "", Toast.LENGTH_SHORT).show();
            }
        });
        addQueue(request);
    }

    /* 定义一个倒计时的内部类 */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            cancelTimeCount();
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            btn_request_sms.setText("倒计时(" + millisUntilFinished / 1000 + ")");
        }
    }

    /**
     * 启动倒计时任务 60秒后自动修改isCheck状态为true
     */
    private void startThread() {
        if (timeCount != null) {
            timeCount.cancel();
            timeCount = null;
        }
        timeCount = new TimeCount(60 * 1000, 1000);
        timeCount.start();
        btn_request_sms.setEnabled(false);
    }

    /**
     * 关闭计时器
     */
    private void cancelTimeCount() {
        //取消倒计时，释放计时器
        if (timeCount != null) {
            timeCount.cancel();
            timeCount = null;
        }
        handler.sendEmptyMessage(1);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                btn_request_sms.setText(getString(R.string.btn_request_sms));
                btn_request_sms.setEnabled(true);
            }
        }
    };
}
